package ru.bytedog.oiot.counter.bot.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.bytedog.oiot.counter.bot.dto.dashboard.UserInfo;
import ru.bytedog.oiot.counter.bot.service.UserService;

import java.util.Optional;

@Controller("serviceUsers")
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public String getUsers(Model view, @RequestParam(value = "page", defaultValue = "1") int page,
                           @RequestParam(value = "size", defaultValue = "10") int size,
                           @RequestParam(value = "sort", required = false) String sort,
                           @RequestParam(value = "order", required = false) String order) {

        Page<UserInfo> usersPage = userService.getAll(getPageParam(page - 1, size, sort, order));
        view.addAttribute("users", usersPage.getContent());
        view.addAttribute("current", usersPage.getNumber() + 1);
        view.addAttribute("total", usersPage.getTotalElements());
        view.addAttribute("totalPages", usersPage.getTotalPages());
        view.addAttribute("firstRowNum", usersPage.getNumber() * usersPage.getSize());
        return "fragments/user/table :: users-table";
    }


    @GetMapping("/{id}")
    public String getUserRegistrationInfo(Model view, @PathVariable("id") Long id) {
        Optional.ofNullable(userService.getByChatId(id))
                .ifPresent(user -> {
                    view.addAttribute("username", user.getUsername());
                    view.addAttribute("serviceId", user.getOiotUserId());
                    view.addAttribute("token", user.getOiotUserToken());
                });
        return "fragments/user/modal :: user-info";
    }

    private PageRequest getPageParam(int page, int size, String sort, String order) {
        if (StringUtils.isBlank(sort)) {
            return PageRequest.of(page, size);
        }
        return PageRequest.of(page, size, Sort.by(Sort.Direction.fromOptionalString(order)
                .orElse(Sort.Direction.ASC), sort));
    }
}
